module AboutYou
  module SDK
    module Model
      ###
      # BasketSetItem is a class used for adding a variant set item into the basket
      ###
      class BasketSetItem
        include AboutYou::SDK::Model::BasketVariantItem
        # erorr code if a product is not included
        ERROR_CODE_PRODUCT_NOT_INCLUDED = 1001

        ###
        # This method is used for creating a basket set item from a given api json
        # response. It is best practice to use this method.
        #
        # * *Args*    :
        #   - +json_object+ -> the api response key
        #   - +products+ -> Array of products
        #
        # * *Returns* :
        #   - an instance of AboutYou::SDK::Model::BasketSetItem
        ###
        def create_from_json(json_object, products)
          item = new(
            json_object['variant_id'],
            if json_object.key?('additional_data')
              [json_object['additional_data']]
            else
              nil
            end,
            json_object.key?('app_id') ? json_object['app_id'] : nil
          )

          item.parse_error_result(json_object)
          item.json_object = json_object

          unless json_object['product_id'].nil?
            if products.key?(json_object['product_id'])
              item.product = products[json_object['product_id']]
            else
              item.errorCode    = ERROR_CODE_PRODUCT_NOT_INCLUDED
              item.errorMessage = 'Product with ID ' +
                json_object['product_id'] + ' expected but wasnt received
                with the basket'
            end
          end

          item
        end
      end
    end
  end
end
